<template>
  <div class="login-container">
    <el-form :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm">
      <i @click="isErweiLogin=!isErweiLogin"
        :class="['jiaobiao', 'iconfont',isErweiLogin?'icon-diannaojiaobiao':'icon-erweimajiaobiao']"></i>
      <div class="common-login"
        v-if="!isErweiLogin">
        <el-form-item label="用户名"
          prop="username">
          <el-input type="text"
            v-model="ruleForm.username"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码"
          prop="password">
          <el-input type="password"
            v-model="ruleForm.password"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码"
          prop="captcha">
          <el-input maxlength=5
            v-model="ruleForm.captcha"
            @keydown.native.enter="submitForm('ruleForm')"
            ref="captcha"></el-input>
          <span class=captcha
            @click="fetchCaptcha"
            v-html="ruleForm.captchaSvg"></span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
            @click="submitForm('ruleForm')">登入</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </div>
      <div class="erwei"
        v-else>
        <p class="p-text">扫描二维码登录</p>
        <div class="img"
          style="background:white">
          <img :src="scanCodeUrl"
            alt="">
          <i class="mask"
            :style="qrStyle"
            v-show="isScanCodeSuccess" @click="getQrcode"></i>
        </div>
      </div>
    </el-form>
  </div>

</template>

<script>
import * as userApi from "../../api/users";
import io from "socket.io-client";
import qrcode from "qrcode";
import { mapMutations } from "vuex";
import codeSuccessImg from '../../assets/img/saomachenggong.png'
import codeInvalidImg from '../../assets/img/saomashibai.png'

var validatecaptcha = (rule, value, callback) => {
  if (!value) {
    callback("验证码不能为空");
  } else {
    callback();
  }
};
var validateusername = (rule, value, callback) => {
  var test = /^[a-zA-Z0-9_-]{3,16}$/;
  if (test.test(value)) {
    callback();
  } else {
    callback("用户名3-16位，数字字母下划线");
  }
};
var validatepassword = (rule, value, callback) => {
  if (!value) {
    callback("密码不能为空");
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      ruleForm: {
        username: "",
        password: "",
        captcha: "",
        captchaSvg: "",
      },
      rules: {
        username: [{ validator: validateusername, trigger: "blur" }],
        password: [{ validator: validatepassword, trigger: "blur" }],
        captcha: [{ validator: validatecaptcha, trigger: "blur" }],
      },
      iconjiaobiao: "",
      isErweiLogin: false,
      qrDataUrl: "",
      scanCodeUrl: "",
      qrStyle: "",
      isScanCodeSuccess: false,
    };
  },
  created() {
    this.fetchCaptcha();
  },
  methods: {
    //获取二维码
    async getQrcode(){
      this.isScanCodeSuccess=false

      let sid = localStorage.getItem("sid")
      let res = await userApi.getQrcodeApi(sid);
      let qrUrl = res.data.scanCodeUrl;
      qrcode.toDataURL(qrUrl, (err, dataUrl) => {
        this.scanCodeUrl = dataUrl;
      });
    },

    //映射vuex的方法
    ...mapMutations(["SET_USERINFO"]),

    //封装一个方法，用于获取验证码
    fetchCaptcha() {
      userApi.getCaptchaApi().then((res) => {
        this.ruleForm.captchaSvg = res.data.img;
      });
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let { username, password, captcha } = this.ruleForm;
          // userApi.loginApi({username,password}).then((res)=>{
          //   console.log(res)
          // })
          userApi.verifyCaptchaApi(captcha.toLowerCase()).then((res) => {
            if (res?.data?.state) {
              userApi.loginApi({ username, password }).then((res) => {
                if (res.data.state) {
                  this.$store.dispatch("FETCH_MENULIST");
                  this.SET_USERINFO(res.data.userInfo);
                  localStorage.setItem(
                    "permission",
                    JSON.stringify(res.data.permission.buttons)
                  );
                  localStorage.setItem("yf-token", res.data.token);
                  localStorage.setItem(
                    "crm-userInfo",
                    JSON.stringify(res.data.userInfo)
                  );
                  this.$router.push("/");
                }
              });
            } else {
              // alert("验证码错误");

              this.ruleForm.captcha = "";
              this.fetchCaptcha();
              this.$refs.captcha.focus();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  watch: {
    isErweiLogin(newV, oldV) {
      if (newV) {
        //切换二维码登入
        //通过socket.io和服务器建立socket连接
        let socket = io("wss://chst.vip");
        //监听socket连接成功事件，发送请求 请求"/users/getScanCode""
        socket.on("connectSuccess", async (data) => {
          // console.log(data);
          let { sid } = data;
          localStorage.setItem("sid", sid);

          this.getQrcode()
          // console.log(res)

          //获取地址获取二维码图片
          // this.getQrcode()
        });

        //监听扫码成功的事件
        socket.on("scancodeSuccess", async (data) => {
          // console.log(data);
          this.isScanCodeSuccess=true
          this.qrStyle={backgroundImage:`url(${codeSuccessImg})`}

          let { wechatCode } = data;
          let res = await userApi.wechatLoginApi(wechatCode);
          console.log(res);
          if(res.data.state){
            this.$store.dispatch("FETCH_MENULIST");
            this.SET_USERINFO(res.data.userInfo);
            localStorage.setItem(
              "permission",
              JSON.stringify(res.data.permission.buttons)
            );
            localStorage.setItem("yf-token", res.data.token);
            localStorage.setItem(
              "crm-userInfo",
              JSON.stringify(res.data.userInfo)
            );
            this.$router.push("/");
          }
        });

        socket.on('invalidCode', data=>{
          console.log(data)
          this.isScanCodeSuccess=true
          this.qrStyle={backgroundImage:`url(${codeInvalidImg})`}

        })

        // 通过qrcode将二维码地址生成二维码
        // 用户扫描二维码，  监听socket事件 scancodeSuccess
        // 请求users/wechatLogin，传递weichatCode
      }
    },
  },
};
</script>

<style lang="less" scoped>
.mask{
  width: 200px;
  height: 200px;
  background: rgba(0, 0, 0, 0.4);
}
.p-text {
  color: #fff;
  text-align: center;
  font-size: 30px;
}
.img {
  width: 200px;
  height: 200px;
  margin-left: 100px;
  i,img{
    display: block;
    width: 200px;
    height: 200px;
  }
  i{
    position: absolute;
    top:90px;
    left:100px;
  }
}
.login-container {
  width: 100%;
  height: 100%;
}
.demo-ruleForm {
  width: 400px;
  height: 400px;
  background: rgba(0, 0, 0, 0.2);
  box-sizing: border-box;
  padding-right: 50px;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  padding-top: 50px;
  /deep/ .el-input__inner {
    width: 250px;
  }
}
.captcha {
  cursor: pointer;
}
.jiaobiao {
  font-size: 50px;
  color: white;
  position: absolute;
  right: 0;
  top: 0;
  cursor: pointer;
}
</style>